package cn.gzjp.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.tools.doclets.formats.html.SourceToHTMLConverter;

public class BaiduAPI {

    /**
     * 计算两点之间距离
     *
     * @param
     * @param
     * @return 千米
     */
    public static String getDistance(Double longitude, Double latitude, Double addressX, Double addressY) {
        double lon1 = (Math.PI / 180) * longitude;
        double lon2 = (Math.PI / 180) * addressX;//经度

        double lat1 = (Math.PI / 180) * latitude;
        double lat2 = (Math.PI / 180) * addressY;//维度

        //地球半径  
        double R = 6371;

        //两点间距离 km，如果想要米的话，结果*1000就可以了  
        double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
        /*        d=d*1000;*/
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(d) + "km";
    }

    /*
     * 获取经纬度
     */
    public static Map<String, Double> getLngAndLat(String address) {
        Map<String, Double> map = new HashMap<String, Double>();
        String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address
                + "&output=json&ak=wPGq8F8k4dvVcm3fXyE4giPF";

        String json = loadJSON(url);
        JSONObject obj = JSONObject.parseObject(json);
        if (obj.get("status").toString().equals("0")) {
            double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
            double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
            map.put("lng", lng);
            map.put("lat", lat);
            System.out.println("经度：" + lng + "---纬度：" + lat);
        } else {
            // System.out.println("未找到相匹配的经纬度！");
        }
        return map;
    }

    /*
     * 请求地图服务器获取经纬度
     */
    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }

    /**
     * 调用百度API接口计算两点驾车距离
     * @param startPointMap
     * @param endPointMap
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> getDistanceByPoints(Map<String, Double> startPointMap, Map<String, Double> endPointMap) {
        Map<String, String> map = new HashMap<String, String>();
        //拼接计算两点驾车距离的百度API接口
        String url = String.format("http://api.map.baidu.com/routematrix/v2/driving?" +
                "output=json&origins=" + startPointMap.get("lat") +
                "," + startPointMap.get("lng") +
                "&destinations=" + endPointMap.get("lat") +
                "," + endPointMap.get("lng") +
                "&ak=dbsQw7WD4V40FFAlVvmo13PC4M2Y2ZEA");
        String json = loadJSON(url);

        System.out.println(json);
        JSONObject obj = JSONObject.parseObject(json);
        if (obj.get("status").toString().equals("0")) {
            JSONArray jsonArray = JSONObject.parseObject(json).getJSONArray("result");
            String distance = jsonArray.getJSONObject(0).getJSONObject("distance").getString("text");
            String duration = jsonArray.getJSONObject(0).getJSONObject("duration").getString("text");
            map.put("distance", distance);
            map.put("duration", duration);
        } else {
            // System.out.println("未找到相匹配的经纬度！");
            getDistanceByPoints(startPointMap,endPointMap);
        }
        return map;
    }

    public static void main(String[] args) {
        Map<String, Double> startMap = BaiduAPI.getLngAndLat("广州");
        Map<String, Double> endMap = BaiduAPI.getLngAndLat("郴州");
//        Map<String,String> distanceMap =  getDistanceByPoints(startMap, endMap);
//        System.out.println(distanceMap.get("distance"));
//        System.out.println(distanceMap.get("duration"));

        System.out.println(Integer.parseInt(getDistance(startMap,endMap))/1000);

//        double longitude = startMap.get("lng");
//        double latitude = startMap.get("lat");
//        double addressX = endMap.get("lng");
//        double addressY = endMap.get("lat");
//        System.out.println(BaiduAPI.getDistance(longitude, latitude, addressX, addressY));
    }


    /**
     * 调用百度API接口计算两点驾车距离
     * @param startPointMap
     * @param endPointMap
     * @return
     */
    @SuppressWarnings("unchecked")
    public static String  getDistance(Map<String, Double> startPointMap, Map<String, Double> endPointMap) {
        Map<String, String> map = new HashMap<String, String>();
        //拼接计算两点驾车距离的百度API接口
        String url = String.format("http://api.map.baidu.com/routematrix/v2/driving?" +
                "output=json&origins=" + startPointMap.get("lat") +
                "," + startPointMap.get("lng") +
                "&destinations=" + endPointMap.get("lat") +
                "," + endPointMap.get("lng") +
                "&ak=dbsQw7WD4V40FFAlVvmo13PC4M2Y2ZEA");
        String json = loadJSON(url);

        System.out.println(json);
        JSONObject obj = JSONObject.parseObject(json);
        if (obj.get("status").toString().equals("0")) {
            JSONArray jsonArray = JSONObject.parseObject(json).getJSONArray("result");
            String distance = jsonArray.getJSONObject(0).getJSONObject("distance").getString("value");
            return distance;
        } else {
            // System.out.println("未找到相匹配的经纬度！");
        }
        return "0";
    }

}
